package top.tenebrous.yzl.im.client;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.stereotype.Component;
import top.tenebrous.yzl.im.utils.WebSocketUtils;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.channels.NotYetConnectedException;
import java.util.ArrayList;
import java.util.List;

/**
 * p2p客户端
 *
 */
@Slf4j
@Component
public class WebSocketHandlerClient {

    //所有客户端WebSocket的连接池
    private List<WebSocket> sockets = new ArrayList<WebSocket>();

    public List<WebSocket> getSockets() {
        return sockets;
    }

    /**
     * 连接到peer
     */
    public void connectPeer(String peer) {
        try {
            /**
             * The WebSocketClient is an abstract class that expects a valid "ws://" URI to connect to. 
             * When connected, an instance recieves important events related to the life of the connection. 
             * A subclass must implement onOpen, onClose, and onMessage to be useful. 
             * An instance can send messages to it's connected server via the send method.
             * 
             * 创建有一个WebSocket的客户端
             */
            final WebSocketClient socketClient = new WebSocketClient(new URI(peer)) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    log.info("客户端--->已连接至新节点:{}", this.uri);
                }

                @Override
                public void onMessage(String msg) {
                    System.out.println("客户端--->收到服务端发送的消息:" + msg);
                }

                @Override
                public void onClose(int i, String msg, boolean b) {
                    sockets.remove(this);
                    WebSocketUtils.removeConnectedSession(this.uri.toString());
                    log.info("客户端--->链接关闭, 移除客户端链接完成：{} 剩余客户端链接:{} 关闭原因:{}", JSON.toJSONString(this.uri), sockets.size(), msg);
                }

                @Override
                public void onError(Exception e) {
                    log.error("客户端--->链接:{} 报错:{}", this.uri, e.getMessage());
                    sockets.remove(this);
                }

                @Override
                public void sendPing() throws NotYetConnectedException {
                    super.sendPing();
                }
            };
            //客户端 开始连接服务端
            socketClient.connect();
        } catch (URISyntaxException e) {
            log.error("客户端--->连接错误:{}", e.getMessage());
        }
    }

}
